package com.example.linearlayoutdemo.avatar;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AvatarRepository {
    private static final String TAG = "AvatarRepository";
    private FileStorageHelper fileStorageHelper;
    private PreferenceHelper preferenceHelper;
    private ExecutorService executor = Executors.newSingleThreadExecutor();
    private Handler mainHandler = new Handler(Looper.getMainLooper());

    public AvatarRepository(Context context) {
        fileStorageHelper = new FileStorageHelper(context);
        preferenceHelper = new PreferenceHelper(context);
    }

    // 从仓库获取用户头像
    public void getAvatar(String userId, AvatarCallback callback) {
        executor.execute(() -> {
            String avatarPath = preferenceHelper.getAvatarPath(userId);
            Bitmap avatarBitmap = fileStorageHelper.getAvatar(avatarPath);
            
            mainHandler.post(() -> {
                if (avatarBitmap != null) {
                    callback.onSuccess(avatarBitmap, avatarPath);
                } else {
                    callback.onFailure("未找到头像");
                }
            });
        });
    }

    // 保存新头像
    public void saveAvatar(String userId, Context context, Uri imageUri, AvatarCallback callback) {
        executor.execute(() -> {
            try {
                // 获取旧头像路径并删除
                String oldPath = preferenceHelper.getAvatarPath(userId);
                if (oldPath != null) {
                    fileStorageHelper.deleteOldAvatar(oldPath);
                }

                // 从Uri获取输入流
                InputStream inputStream = context.getContentResolver().openInputStream(imageUri);
                if (inputStream == null) {
                    mainHandler.post(() -> callback.onFailure("无法获取图片"));
                    return;
                }

                // 保存新头像
                String newPath = fileStorageHelper.saveAvatar(userId, inputStream);
                inputStream.close();

                if (newPath != null) {
                    // 保存路径到SharedPreferences
                    preferenceHelper.saveAvatarPath(userId, newPath);
                    Bitmap newAvatar = fileStorageHelper.getAvatar(newPath);
                    
                    mainHandler.post(() -> {
                        if (newAvatar != null) {
                            callback.onSuccess(newAvatar, newPath);
                        } else {
                            callback.onFailure("保存头像失败");
                        }
                    });
                } else {
                    mainHandler.post(() -> callback.onFailure("保存头像失败"));
                }
            } catch (IOException e) {
                Log.e(TAG, "保存头像异常: " + e.getMessage());
                mainHandler.post(() -> callback.onFailure("保存头像异常: " + e.getMessage()));
            }
        });
    }

    // 头像操作回调接口
    public interface AvatarCallback {
        void onSuccess(Bitmap avatar, String path);
        void onFailure(String errorMessage);
    }
}
